package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ArticleCache;
import com.heima.article.entity.ArticleStreamMessage;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.IComputeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ComputeServiceImpl implements IComputeService {
    @Autowired
    private IApArticleService apArticleService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void compute() {
        System.out.println("热点文章加载...........,"+new Date());

//        查询数据
        LambdaQueryWrapper<ApArticle> query = new LambdaQueryWrapper<>();
//        查询距现在前五天的
        Date now = new Date();
        Date end = new Date(now.getYear(),now.getMonth(),now.getDate());
        Date start = new Date(end.getTime() - 24 * 60 *60 *1000);
        query.lt(ApArticle::getPublishTime,end);
        query.gt(ApArticle::getPublishTime,start);
//        排除 已下架 和 以撒喊出的商品
        query.eq(ApArticle::getIsDelete,false);
        query.eq(ApArticle::getIsDown,false);
        List<ApArticle> list = apArticleService.list(query);

        for (ApArticle apArticle : list) {
            double score = computeScore(apArticle);

            String key = "hot_article_0";
            ArticleCache articleCache = new ArticleCache();
            BeanUtils.copyProperties(apArticle,articleCache);
            String value = JSON.toJSONString(articleCache);
            redisTemplate.opsForZSet().add(key,value,score);

            String channelKey = key+apArticle.getChannelId();
            redisTemplate.opsForZSet().add(channelKey,value,score);

            redisTemplate.expire(key,23 * 60 +58, TimeUnit.MINUTES);
            redisTemplate.expire(channelKey,23 * 60 +58, TimeUnit.MINUTES);
        }


    }

    @Override
    public void Update(ArticleStreamMessage message) {
        System.err.println(message);
//        查询文章
        ApArticle article = apArticleService.getById(message.getArticleId());
//        计算分值
        double voluePuls = ScoreValue(message);
        String key = "hot_article_" + article.getChannelId();
        ArticleCache articleCache = new ArticleCache();
        BeanUtils.copyProperties(article,articleCache);
        String value = JSON.toJSONString(articleCache);
        Double score = redisTemplate.opsForZSet().score(key, value);
        if (score == null){
//            以前不存在分值
            double hisScore = computeScore(article);
            double totalScore = voluePuls+hisScore;
            redisTemplate.opsForZSet().add(key,value,totalScore);
            redisTemplate.opsForZSet().add("hot_article_0",value,totalScore);

//            设置过期时间
            redisTemplate.expire(key,23 * 60 +58,TimeUnit.MINUTES);
            redisTemplate.expire("hot_article_0",23 * 60 + 58,TimeUnit.MINUTES);
        }else {
            redisTemplate.opsForZSet().add(key,value,voluePuls);
            redisTemplate.opsForZSet().add("hot_article_0",value,voluePuls);
        }
//        更新数据库文章
        LambdaUpdateWrapper<ApArticle> update = new LambdaUpdateWrapper<>();
        update.eq(ApArticle::getAuthorId,message.getArticleId());
        update.setSql("views = views +"+ message.getView());
        update.setSql("likes = likes +"+ message.getLike());
        update.setSql("comment = comment +"+ message.getComment());
        update.setSql("collection = collection +"+ message.getCollect());
        apArticleService.update(update);


    }
//    计算分值
    private double ScoreValue(ArticleStreamMessage message) {
        double score =  0;
        score += message.getView() * 1 * 3;
        score += message.getLike() * 3 * 3;
        score += message.getComment() * 5 * 3;
        score += message.getCollect() * 8 * 3;
        return  score;
    }

    private double computeScore(ApArticle apArticle) {
        // 阅读+1 点赞+3 评论+5 收藏+8
        double score = 0;
        if (apArticle.getViews() != null){
            score += apArticle.getViews() * 1;
        }
        if (apArticle.getLikes() != null){
            score += apArticle.getLikes() * 3;
        }
        if (apArticle.getComment() != null){
            score += apArticle.getComment() * 5;
        }
        if (apArticle.getCollection() != null){
            score += apArticle.getCollection() * 8;
        }
        return score;
    }
}
